package com.copro.chemdb.stat.rule;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;

import org.ihelpuoo.db.sql.SQLSegment;
import org.ihelpuoo.localize.Localize;
import org.ihelpuoo.util.Properties;

import com.copro.chemdb.stat.StatResult;
import com.copro.chemdb.stat.StatRule;
import com.copro.chemdb.subject.Subject;
import com.copro.simple.Application;
import com.copro.simple.SimpleException;
import com.copro.simple.db.QueryCallback;
import com.copro.simple.db.QuickQueryCallback;

public class Rule7 implements StatRule {

	private Properties conf;

	@Override
	public StatResult doStat(Application app, Subject subject, int type)
			throws SimpleException {
		SQLSegment sql = app.getSQL("rule7CountProv");
		sql.set("subjectId", subject.getId());
		sql.set("type", type);
		List<List<String>> provs = new LinkedList<List<String>>();
		QueryCallback callback = new QuickQueryCallback(provs) {
			@SuppressWarnings("unchecked")
			@Override
			public void exec(ResultSet rs) throws SQLException {
				while (rs.next()) {
					List<String> list = new ArrayList<String>(2);
					list.add(rs.getString(1));
					list.add(rs.getString(2));
					((List) obj).add(list);
				}
			}
		};
		app.query(sql.toString(), callback);

		sql = app.getSQL("rule7CountArea");
		sql.set("subjectId", subject.getId());
		sql.set("type", type);
		List<List<String>> parts = new ArrayList<List<String>>();
		callback = new QuickQueryCallback(parts) {
			@SuppressWarnings("unchecked")
			@Override
			public void exec(ResultSet rs) throws SQLException {
				while (rs.next()) {
					List<String> list = new ArrayList<String>(2);
					list.add(Localize.convertAscii2Native(conf
							.getStringTrimed(rs.getString(1))));
					list.add(rs.getString(2));
					((List) obj).add(list);
				}
			}
		};
		app.query(sql.toString(), callback);
		sql = app.getSQL("rule7CountALL");
		sql.set("subjectId", subject.getId());
		sql.set("type", type);
		int count = app.getCount(sql.toString());

		Hashtable<String, Object> result = new Hashtable<String, Object>();

		result.put("province", provs);
		result.put("parts", parts);
		result.put("count", String.valueOf(count));
		result.put("text", subject.getBrief());
		return new StatResult("rule7", result);
	}

	@Override
	public void setup(Properties conf) {
		this.conf = conf;
	}

}
